
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Web.UI;
using AdventureWorks.Client.Objects;
using AdventureWorks.Services;
using Xomega.Framework;
using Xomega.Framework.Web;

namespace AdventureWorks.Client.Web
{
    public partial class EmployeeSearch : Page
    {
        private EmployeeCriteria criteria;
        private EmployeeRowObject list;

        protected void Page_Init(object sender, EventArgs e)
        {
            criteria = WebUtil.GetCachedObject<EmployeeCriteria>(
              "criteria:" + Request.CurrentExecutionFilePath, !WebUtil.IsPostRequest());
            pnlCriteria.DataBind();
            WebUtil.BindToObject(pnlCriteria, criteria);
            list = WebUtil.GetCachedObject<EmployeeRowObject>(
              "list:" + Request.CurrentExecutionFilePath, !WebUtil.IsPostRequest());
            list.Editable = false;
            WebUtil.BindToList(grdResults, list);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack && Request["run"] != null)
              btnSearch_Click(null, null);
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            criteria.Validate(true);
            ErrorList valErr = criteria.GetValidationErrors();
            errors.List.DataSource = valErr.Errors;
            errors.List.DataBind();
            if (valErr.HasErrors()) return;

            IEmployeeService svcEmployee = new AdventureWorks.Services.EmployeeService();
            try
            {
                Employee_ReadListInput inReadList = new Employee_ReadListInput();
                criteria.ToDataContract(inReadList);
                IEnumerable<Employee_ReadListOutput> outReadList;
                using (TimeTracker.ServiceCall)
                    outReadList = svcEmployee.ReadList(inReadList);
                list.FromDataContract(outReadList);
            }
            catch (Exception ex)
            {
                errors.List.DataSource = ErrorList.FromException(ex).Errors;
                errors.List.DataBind();
            }
            finally
            {
                if (svcEmployee is IDisposable) ((IDisposable)svcEmployee).Dispose();
            }
        }

        protected void btnReset_Click(object sender, EventArgs e)
        {
            list.Clear();
        }
    }
}
